//
//  ViewController.swift
//  表情键盘
//
//  Created by ffxk007 on 2017/7/10.
//  Copyright © 2017年 ffxk007. All rights reserved.
// Cannot use instance member 'str' within property initializer; property initializers run before 'self' is available

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var textView: UITextView!
    lazy var emoticonView:CZEmoticonInputView = CZEmoticonInputView.inputView { [weak self] (emoticon) in
        
        self?.insertEmoticon(em: emoticon)
    }
    
    /// 向文本视图插入表情符号[图文混排]
    ///
    /// - Parameter em: 选中的表情符号，nil表示删除
    func insertEmoticon(em:CZEmoticon?) {
        //1.em等于nil是删除按钮
        guard let em = em else {
            //删除文本
            textView.deleteBackward()
            
            return
        }
        
        //2.emoji 字符串
        if let emoji = em.emoji,let textRange = textView.selectedTextRange {
            
            //UITextRange仅仅用在此处
            textView.replace(textRange, withText: emoji)
            return
            
        }
        //代码执行到此 都是图片表情
        //0.获取表情中的图像属性文本
        //几乎所有的排版系统中，都有一个共同的特点，插入的字符的显示，跟随前一个字符的属性，但是本身没有属性
//        let imageText = NSMutableAttributedString(attributedString: em.imageText(font: textView.font!))
//        //设置图像文字的属性
//        imageText.addAttributes([NSFontAttributeName:textView.font!], range: NSRange(location: 0, length: 1))

        let imageText = em.imageText(font: textView.font!)
        
        //1.获取当前textview的属性文本-可变的
        let attrStrM = NSMutableAttributedString(attributedString: textView.attributedText)
        //2.将图像的属性文本插入到当前的光标位置
        attrStrM.replaceCharacters(in: textView.selectedRange, with: imageText)
        //3.重新设置属性文本
        //记录光标位置
        let range = textView.selectedRange
        //设置文本
        textView.attributedText = attrStrM
        //恢复光标位置,length是选中字符的长度，插入文本后为0
        textView.selectedRange = NSRange(location: range.location + 1, length: 0)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        textView.inputView = emoticonView
        textView.reloadInputViews()
        
    }
    

    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }

}

